package com.itheima.controller;

import com.itheima.jopo.PageBean;
import com.itheima.jopo.Result;
import com.itheima.jopo.Student;
import com.itheima.service.StudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * StudentController
 *
 * @author liliudong
 * @version 1.0
 * @description StudentController
 * @date 2023/5/1 11:04
 */
@RestController
@RequestMapping("/student")
@RequiredArgsConstructor
public class StudentController {

    private final StudentService studentService;

    @PostMapping
    public Result create(@RequestBody Student student) {
        Boolean studentNumberExist = studentService.existByStudentNumber(student.getStudentNumber());
        if (studentNumberExist) {
            return Result.error("学号重复");
        }
        Boolean phoneExist = studentService.existByPhone(student.getPhone());
        if (phoneExist) {
            return Result.error("手机号已存在");
        }
        studentService.save(student);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        studentService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result queryById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        return Result.success(student);
    }

    @PutMapping
    public Result modifyById(@RequestBody Student student) {
        Boolean studentNumberExist = studentService.checkStudentNumberRepeat(student.getStudentNumber());
        if (studentNumberExist) {
            return Result.error("学号重复");
        }
        Boolean phoneExist = studentService.checkPhoneRepeat(student.getId(), student.getPhone());
        if (phoneExist) {
            return Result.error("手机号已存在");
        }
        studentService.updateById(student);
        return Result.success();
    }

    @PutMapping("/deductions")
    public Result deductions(@RequestBody Student student) {
        if (student.getDisciplineScore() <= 0) {
            return Result.error("扣除的分数必须大于0");
        }
        studentService.deductions(student);
        return Result.success();
    }

    @GetMapping
    public Result page(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                       String name,
                       Integer highestDegree,
                       Integer classesId,
                       String studentNumber) {
        PageBean pageBean = studentService.page(page, pageSize, name, highestDegree, classesId, studentNumber);
        return Result.success(pageBean);
    }
}
